<?php
class ClientScript extends CClientScript{	
	public $packages = array(
		'yiiactiveform' => array(
			'js' => array('js/plugins/yii/yiiactiveform.js'),
			'depends' => array('jquery'),
			'basePath' => 'views.layouts.static'
		),
		
	);
	/**
	 * 是否开启Core.js模式
	 * @var boolean
	 */
	public $enableCoreJs = true;
	
	/**
	 * 编译less文件
	 * @param string $path less文件路径
	 * @param @param string $media media that the CSS file should be applied to. If empty, it means all media types.
	 * @throws CException
	 * @return Ambigous <CClientScript, CClientScript>
	 */
	public function registerLessFile($path, $media = '', $show = false){
		$app = Yii::app();
		if($controller = $app->controller){
			$fileName = pathinfo($path, PATHINFO_FILENAME);
			$fileName = sprintf('%x',crc32($path)) . '-' . $fileName . (YII_DEBUG ? '' : '.min') . '.css';
			
			$url = $app->asset->getBaseAsset() . '/css/' . $fileName;
			
			if (!is_file($url) || @filemtime($path) > @filemtime($url)) {
				Yii::import('ext\phpLess\lessc', true);
				$less = new lessc;
				!YII_DEBUG && $less->setFormatter("compressed");
				$less->checkedCompile($path, $url);
			}
			if($show)
				echo CHtml::cssFile($url, $media)."\n";
			else
				$this->registerCssFile($url, $media);
			return $this;
		}
			throw new CException(Yii::t('Yii', 'Can not compile less file, controller is not exists or less is not work'));
	}
	
	/**
	 * Core.js 支持
	 * @see CClientScript::render()
	 */
	public function render(&$output){
		if(!$this->hasScripts)
			return;
	
		$this->renderCoreScripts();
	
		if(!empty($this->scriptMap))
			$this->remapScripts();
	
		$this->unifyScripts();
	
		if($this->enableCoreJs)
			$this->renderWithCoreJs($output);
		else{
			$this->renderHead($output);
			if($this->enableJavaScript)
			{
				$this->renderBodyBegin($output);
				$this->renderBodyEnd($output);
			}
		}
	}
	
	/**
	 * Core.js的渲染方式(全部渲染在页面底部)
	 * 
	 * 此方式牺牲很多外部资源自由性.但是好处是可以指加载一个core.js文件.并行加载和和处理文件.提升用户体验
	 */
	public function renderWithCoreJs(&$output){
		$coreJs = $headHtml = $html = '';
				
		if($this->enableJavaScript){
			$postions = array(self::POS_HEAD, self::POS_BEGIN, self::POS_END, self::POS_LOAD, self::POS_READY);
			$output = preg_replace('/(<\\/body\s*>)/is','<###end###>$1', $output, 1, $fullPage);
			$scripts = $scriptFiles = array();
			foreach($postions as $postion){
				if(isset($this->scriptFiles[$postion]))
					$scriptFiles = array_merge($scriptFiles, $this->scriptFiles[$postion]);
				
				if(($postion == self::POS_LOAD) && isset($this->scripts[$postion]) && $fullPage)
					$scripts[] = "jQuery(window).load(function() {\n" . implode("\n", $this->scripts[$postion]) . "\n});";
				elseif(($postion == self::POS_READY) && isset($this->scripts[$postion]) && $fullPage)
					$scripts[] = "jQuery(function($) {\n" . implode("\n", $this->scripts[$postion]) . "\n});";
				elseif(isset($this->scripts[$postion]))
					$scripts[] = implode("\n", $this->scripts[$postion]);
			}
			$script = !empty($scripts) ? ", function(){\n" . implode("\n", $scripts) . "\n}" : '';
			$scriptFiles = !empty($scriptFiles) ? "'" . implode("', '", $scriptFiles) . "'" : '';
			$html .= CHtml::script("Core.use(" . $scriptFiles . $script . ");");
			
			if($fullPage)
				$output = str_replace('<###end###>', $html, $output);
			else
				$output = $output.$html;
			
			$app = Yii::app();
			if(!$app->request->getIsAjaxRequest()){
				$coreJs = CHtml::scriptFile($app->asset->getBaseAsset() . '/js/core.js')."\n";
			}
		}

		foreach($this->metaTags as $meta)
			$headHtml.=CHtml::metaTag($meta['content'],null,null,$meta)."\n";
		foreach($this->linkTags as $link)
			$headHtml.=CHtml::linkTag(null,null,null,null,$link)."\n";
		foreach($this->cssFiles as $url=>$media)
			$headHtml.=CHtml::cssFile($url,$media)."\n";
		foreach($this->css as $css)
			$headHtml.=CHtml::css($css[0],$css[1])."\n";
		
		$headHtml .= $coreJs;
		
		if($headHtml!==''){
			$count=0;
			$output=preg_replace('/(<title\b[^>]*>|<\\/head\s*>)/is','<###head###>$1',$output,1,$count);
			if($count)
				$output=str_replace('<###head###>',$headHtml,$output);
			else
				$output=$headHtml.$output;
		}
	}
}